package com.ellfors.common.http

import com.ellfors.common.constant.HttpConstants
import com.ellfors.common.http.utils.HttpLogUtil
import com.ellfors.common.http.utils.NetBuilder
import okhttp3.logging.HttpLoggingInterceptor

object HttpFactory {

    private val builder by lazy {
        NetBuilder().apply {
            setConnectTimeout(15)
            setReadTimeout(15)
            setWriteTimeout(15)
            setRetryOnConnectionFailure(true)
            setSslFactory()
        }
    }

    private val mLoggingInterceptor: HttpLoggingInterceptor by lazy {
        HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                HttpLogUtil.log("MyTest", message)
            }
        }).apply {
            setLevel(HttpLoggingInterceptor.Level.BODY)
        }
    }

    fun <T> createApi(clz: Class<T>, hostUrl: String = HttpConstants.HOST, openLog: Boolean = true): T {
        val retrofit = builder
        if (openLog) {
            retrofit.addLogInterceptor()
        }
        return retrofit.build(hostUrl).create(clz)
    }

    private fun NetBuilder.addLogInterceptor() {
        addInterceptor(HttpLoggingInterceptor().apply {
            setLevel(HttpLoggingInterceptor.Level.BODY)
        })
        addInterceptor(mLoggingInterceptor)
    }
}